﻿using Castle.Windsor;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Castle.Windsor.Installer;
using KaytechSoftware.Cms.App.App_Start;
using KaytechSoftware.Cms.Common.Helpers;
using KaytechSoftware.Cms.Windsor;

namespace KaytechSoftware.Cms.App
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        private static readonly IWindsorContainer Container = new WindsorContainer();

        protected void Application_Start()
        {
            InitializeWindsorContainer();
            AreaRegistration.RegisterAllAreas();
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new CmsViewEngine());

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            PathHelper.Server = Server;
        }

        private static void InitializeWindsorContainer()
        {
            Container.Install(FromAssembly.This());
            InitializeModuleServices();
            var controllerFactory = new WindsorControllerFactory(Container.Kernel);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);
        }

        private static void InitializeModuleServices()
        {
            Container.Install(ServiceInstallersProvider.ServiceInstallers);
        }

        protected void Application_End()
        {
            Container.Dispose();
        }
    }
}